<?php
/**
 * LdapException
 */

namespace Ldap;


/**
 * LdapException
 * @package Ldap
 *
 * @method LdapException(string | resource $mixed, int $code)
 */
class LdapException extends \Exception
{
    /**
     * LDAP Exception.
     *
     * @param string | resource $mixed
     *   Error message.
     * @param int $code
     *   Error code.
     */
    public function __construct($mixed, $code = 0)
    {
        if (is_resource($mixed)) {
            parent::__construct(ldap_error($mixed), ldap_errno($mixed));
        } else {
            parent::__construct($mixed, $code);
        }
    }

    public function __toString()
    {
        $error = __CLASS__ . ": Error code {$this->code}: {$this->message}\n";
        $error .= "Stack trace:\n";
        $count = 0;
        foreach ($this->getTrace() as $trace) {
            if ($trace['file'] != __FILE__) {
                $args = implode(', ', array_map(function ($item) {
                    $type = gettype($item);
                    return $type == 'object' ? get_class($item) : $type;
                }, $trace['args']));
                $error .= "#$count ";
                $error .= "${trace['file']}(${trace['line']}): ";
                $error .= "${trace['class']}${trace['type']}";
                $error .= "${trace['function']}(${args})\n";
                $count++;
            }
        }
        return $error;
    }
}